package com.xw.hchat.netty;

import io.netty.channel.Channel;
import org.apache.commons.lang3.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 建立用户id与通道的关联
 * @ClassName UserChannelMap
 * @Author liu zhiyong
 * @Date 2020/8/19 14:06
 * @Version 1.0
 */
public class UserChannelMap {
    private static Map<String, Channel> userChannelMap;

    static {
        userChannelMap = new HashMap<String, Channel>();
    }

    /**
     * 添加用户id与通道的关联
     * @Author liu zhiyong
     * @Date 2020/8/19 14:09
     * @param userid
     * @param channel
     * @return void
     **/
    public static void put(String userid, Channel channel){
        userChannelMap.put(userid, channel);
    }

    /**
     * 移除用户id与通道的关联
     * @Author liu zhiyong
     * @Date 2020/8/19 14:10
     * @param userid 
     * @return void 
     **/
    public static void remove(String userid){
        userChannelMap.remove(userid);
    }

    /**
     * 根据通道的id移除与用户的关联
     * @Author liu zhiyong
     * @Date 2020/8/19 15:12
     * @param channelId
     * @return void
     **/
    public static void removeByChannelId(String channelId){
        if(!StringUtils.isNotBlank(channelId)){
            return;
        }
        for (String key : userChannelMap.keySet()) {
            Channel channel = userChannelMap.get(key);
            if(channelId.equals(channel.id().asLongText())){

                System.out.println("客户端连接断开，取消用户" + key + "与通道" + channelId + "的关联");
                userChannelMap.remove(key);
                break;
            }
        }
    }

    /**
     * 打印所有用户与通道的关联信息
     * @Author liu zhiyong
     * @Date 2020/8/19 14:15
     * @param
     * @return void
     **/
    public static void print(){
        System.out.println("=============现存用户与通道的关联信息=================");
        for (String key : userChannelMap.keySet()) {
            System.out.println("用户id：" + key + " 通道：" + userChannelMap.get(key).id());
        }
        System.out.println("===============================================");
    }

    /**
     * 根据用户id，获取对应的通道
     * @Author liu zhiyong
     * @Date 2020/8/19 16:06
     * @param userid 用户id
     * @return io.netty.channel.Channel Netty通道
     **/
    public static Channel get(String userid) {
        return userChannelMap.get(userid);
    }
}
